# coding: utf-8
import time, sys
from optparse import make_option
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from enbook.games.models import Domains, Games
from enbook.games import Loader

# Модуль обновляет список игр всех доменов. Если указана опция --forceall, то загружается полный список игр домена (без опции - только первая страница прошедших игр) 

class Command(BaseCommand):
    help = u'Updates games list for domains'
    option_list = BaseCommand.option_list + (
        make_option('--forceall', default=False, action='store_true',
            help=u'Force to inspect all gamepages of domain (slow).'),
        make_option('--verbose', default=False, action='store_true',
            help=u'Show progress messages.'),
    )

    def storeGameList(self,gameList, domain):
        u" Сохраняет список игр домена "
        cdate = time.strftime("%Y-%m-%d %H:%M:%S")
        successCount = 0
        for item in gameList:
            gameName = unicode(item['gameName'],"utf-8").encode('utf-8')
            try:
                game = Games.objects.get(id=item['gameID'])
                continue # Пропускаем игры, уже существующие в базе
            except ObjectDoesNotExist:
                game = Games(id=item['gameID'])
                game.game_name = gameName
                game.game_num = item['gameNumber']
                game.game_date = item['gameDate']
                game.game_date_str = item['gameDateStr']
                game.domain = domain
                game.game_type = item['gameType']
                game.game_zone = item['gameZone']
                game.added = cdate
                game.save()
                successCount += 1
        domain.updated = cdate
        domain.save()
        return successCount
    
    def handle(self, *args, **options):
        u" Точка входа при выполнении команды "
        
        fastUpdate = not options.get('forceall',False)
        verbose = options.get('verbose',False)
        
        if fastUpdate == True:
            domains = Domains.objects.extra(where=['(`updated` IS NULL) OR (DATEDIFF(NOW(),`updated`) > 2)']).order_by('updated')
        else:
            domains = Domains.objects.all().order_by('updated')
        for d in domains:
            if verbose: print u'fetching %s games...' % (d.domain_name,), 
            Loader.fast = fastUpdate # флаг Быстрого обновления (качать только первую страницу списка игр)
            games = Loader.getGames(d.domain_name)
            if games != None:
                successCount = self.storeGameList(games, d)
                if verbose: print successCount, u'saved'
            else:
                if verbose: print u'nothing to save'
